var treeNodeId = null;
Ext.define("component.room.switchTab",{
	extend : 'Ext.panel.Panel',
	config : {
		treeId : ''
	},
	initComponent:function(){
		var me = this;
		var treeId = this.treeId;
		treeNodeId=treeId;
		var dataView = clickTree(treeId);
		var defaultConfig = {
				defaults: {  
		            split: false,    //有分割线  
		            collapsible: false  //可以折叠
		        },
			items:[dataView]
		};
		Ext.apply(this,defaultConfig);
		this.callParent();
		
	}
});

function getStrId(str){
	if(str==null||str==""){
		return null;
	}
	return str.substring(str.indexOf("_")+1,str.length);
}
function clickPanle(treeId){
	clickTree(treeId);
}
function createHtmlPanle(html){
	return Ext.create('Ext.Panel', {
		 frame: true,
        collapsible: true,
        width:250,
        collapsible: false,//可折叠  
        layout:'column',
        bodyStyle:'background:#66CD00',
        html:html,
	    defaults:{
   	        border:false        //去掉panel的边框  
   	    }
	});
}
function clickTree(id){
	
	var treePrefix = id.substring(0,id.indexOf("_"));
	var buildingId=null;
	var unitId = null;
	var roomId = null;
	var areaId = null;
	var carportId = null;
	var projectId = null;
	var premises = null;
	switch(treePrefix){
	case 'BUILDING':
		buildingId=id;
	  break;
	case 'UNIT':
		unitId=id;
	  break;
	case 'ROOM':
		roomId=id;
	break;
	case 'CARAREA':
		areaId=id;
		break;
	case 'CARPORT':
		carportId=id;
		break;
	case 'PROJECT':
		projectId=id;
		break;
	case 'PREMISES':
		premises=id;
		break;
	default:
		 break;
	}
	if(/*treePrefix=="BUILDING"||*/treePrefix=="UNIT"||treePrefix=="ROOM"){
		roomList(buildingId,unitId,roomId);
	}else if(treePrefix=="PREMISES"|| treePrefix=="PROJECT" || treePrefix=="BUILDING"){
		//对别墅直接到房间兼容处理(ym)
		if(treePrefix=="BUILDING"){
			var treeNodeInterface = Ext.getCmp("menuTree").getStore().getNodeById(id);
			var childNodes=treeNodeInterface.childNodes;
			var unitCount=0;
			for(var i=0;i<childNodes.length;i++){
				var nextChildNodes=childNodes[i].childNodes;
				if(nextChildNodes.length>0){
					//说明有单元层级
					unitCount=unitCount+1;
				}
			}
			if(unitCount==childNodes.length){
				//楼栋下面全部是单元
			}else if(unitCount==0){
				//楼栋下面全部是房间，跳转房间界面
				roomList(buildingId,unitId,roomId);
				return;
			}else{
				Ext.Msg.alert('提示', '楼栋下同时存在单元和房间，无法显示！');
				return;
			}
		}
		
		//对别墅直接到房间兼容处理(ym)
		var p_id =getStrId(projectId);
		var r_id = getStrId(premises);
		var b_id = getStrId(buildingId);
		Ext.Ajax.request({
			url: jypath+'/marketing/room/findProjectBuilding',
			params:{
				'premises':r_id,
				'projectId':p_id,
				'buildingId':b_id,
				'resourcesCode': 'menu_0003_0001,menu_0005_0004'
			},
			 callback: function (options, success, response) {
				 var result = JSON.parse(response.responseText);
				 	if(Ext.getCmp("allInfoBody")!=undefined){
				 		Ext.getCmp("allInfoBody").removeAll();
						Ext.getCmp("detailInfoBody").removeAll();
				 	}else{
				 		Ext.getCmp("centerBody").add(createTop());
				 		Ext.getCmp("centerBody").add(createButton());
				 	}
					
					if(result.res==1){
					 if(!result.obj){
						 Ext.Msg.alert('提示', '无下级数据!');
						 return false;
					 }
					 for(var i=0;i<result.obj.length;i++){
						 var obj = result.obj[i];
						 var method="clickPanle('"+obj.id+"')";
						 var html='<div style="width:250px;height:140px;" onclick='+method+'>';
						 html += '<h1 style="text-align:center" >'+obj.name+'</h1>';
						 html += '</div>';
						 var pObj =  createHtmlPanle(html);
						 Ext.getCmp("detailInfoBody").add(pObj);
					 }
					 //查询房间状态数
	        		 findRoomFooter(projectId, premises, buildingId, unitId, roomId);
				 }else if(result.res==100){
					  Ext.Msg.alert('提示', '没有查询权限,请联系管理员!');
				 }
			 }
		});
		var footer = Ext.getCmp("staticFooter");
		if(footer!=undefined&&footer!=null){
			footer.hide();
		}
	}
}

function roomList(buildingId,unitId,roomId){
	if(Ext.getCmp("allInfoBody")!=undefined){
 		Ext.getCmp("allInfoBody").removeAll();
		Ext.getCmp("detailInfoBody").removeAll();
 	}else{
 		Ext.getCmp("centerBody").add(createTop());
 		Ext.getCmp("centerBody").add(createButton());
 	}
	var params = {
			'buildingId':buildingId,
			'unitId':unitId,
			'roomId':roomId,
			'resourcesCode': 'menu_0003_0001,menu_0005_0004'
			};
	Ext.Ajax.request({
		url: jypath+'/marketing/room/findMarketingList',
		params:params,
		method: 'POST',
        callback: function (options, success, response) {
        	  var result = JSON.parse(response.responseText);
        	  if(result.res==1){
        		  Ext.getCmp("detailInfoBody").add(createInfo(result.obj));
        		  //查询房间状态数
        		  findRoomFooter("", "", buildingId, unitId, roomId);
        		  //查询认购签约占比
    			  //proportionList("", "", buildingId, unitId, roomId);
        	  }else if(result.res==100){
        		  Ext.Msg.alert('提示', '没有查询权限,请联系管理员!');
        	  }
          }
	});
}
//查询房间状态数
function findRoomFooter(projectId, premisesId, buildingId, unitId, roomId){
	var footerParams={
		'projectId': getStrId(projectId),
		'buildingId': getStrId(buildingId),
		'premisesId': getStrId(premisesId),
		'unitId': getStrId(unitId),
		'id': getStrId(roomId),
		'resourcesCode': 'menu_0003_0001,menu_0005_0004'
	};
	Ext.Ajax.request({
		  url: jypath+'/marketing/room/findRoomFooter',
		  params:footerParams,
		  method: 'POST',
		  async : false,
		  callback: function (options, success, response) {
		  	  var obj = JSON.parse(response.responseText);
		  	  var html="";
		  	  for(var i=0;i<obj.length;i++){
		  		  html+=footerHtml(obj[i].color, obj[i].status, obj[i].number);
		  	  }
		  	  //创建统计页脚
		  	  var footerPanle = Ext.getCmp("staticFooter");
		  	  if(footerPanle==null||footerPanle==undefined){
		  		  footerPanle= staticfooter();
		  		  Ext.getCmp("allInfoBody").add(footerPanle);
		  	  }else{
		  		  footerPanle.show();
		  	  }
		  	  Ext.getCmp("staticFooter").body.update(html);
		  	  //查询认购签约占比
			  proportionList(projectId, premisesId, buildingId, unitId, roomId);
		  }
    });
}
function footerHtml(color,status,number){
	var html = "";
	if("认筹" == status && payDepositOff){
		//payDepositOff: 认筹相关开关已关闭
	}else{
		html = "<div>";
		html += "<span style='float:left;display:block;width:25;height:15px;background:"+color+" ' ></span>";
		html += "<font  style='float:left; margin:0 10px;display:block'>"+status+":"+number+"</font>";
		html += "</div>";
	}
	return html;
}
function staticfooter(){
	return Ext.create('Ext.Panel', {
		id:'staticFooter',
        frame: true,
        collapsible: true,
        autoScroll:true,
        header:false,
        height:30
        
    });
}
//获取占比列表数据
function proportionList(projectId, premisesId, buildingId, unitId, roomId){
	var params = {
		'projectId': getStrId(projectId),
		'buildingId': getStrId(buildingId),
		'premisesId': getStrId(premisesId),
		'unitId': getStrId(unitId),
		'roomId': getStrId(roomId),
		'resourcesCode': 'menu_0003_0001,menu_0005_0004'
	};
	Ext.Ajax.request({
		url: jypath+'/marketing/room/findProportion',
		params:params,
		method: 'POST',
        callback: function (options, success, response) {
        	var obj = JSON.parse(response.responseText);
        	var html = "";
        	if(obj.res == "1"){
        		html = proportionTable(obj.obj);
        	}
        	//创建占比列表框
      	    var footerPanle = Ext.getCmp("proportionFooter");
      	    if(footerPanle==null||footerPanle==undefined){
      		   footerPanle= proportion();
      		   Ext.getCmp("allInfoBody").add(footerPanle);
      	    }else{
      		   footerPanle.show();
      	    }
      	    Ext.getCmp("proportionFooter").body.update(html);
        }
    });
}
//占比列表框
function proportionTable(data){
	var html = "<span><strong>认购数量占比:</strong>&nbsp;&nbsp;&nbsp;"+data.subscribeTotalRatio+"%</span><span><strong>&nbsp;&nbsp;&nbsp;认购金额:</strong>&nbsp;&nbsp;&nbsp;"+data.subscribeAmount+"&nbsp;(万元)</span>"
	html+="<span><strong>&nbsp;&nbsp;&nbsp;签约数量占比:</strong>&nbsp;&nbsp;&nbsp;"+data.signedTotalRatio+"%</span><span><strong>&nbsp;&nbsp;&nbsp;签约金额:</strong>"+data.signedAmount+"&nbsp;(万元)</span>";
	return html;
}
//占比列表框
function proportion(){
	return Ext.create('Ext.Panel', {
		id:'proportionFooter',
        frame: true,
        collapsible: true,
        autoScroll:true,
        header:false,
        height:150
    });
}

function createInfo(obj){
	if(!obj){
		Ext.Msg.alert('提示', '无下级数据!');
		return false;
	}
	for(var i=0;i<obj.length;i++){
		var unit = createPanle(obj[i].unitName);
		Ext.getCmp("detailInfoBody").add(unit);
	  	for(var j=0;j<obj[i].roomView.length;j++){
		  	var roomObj = obj[i].roomView[j];
		  	var houseType = roomObj.roomType==null?"":roomObj.roomType;
		  	var str = roomObj.roomName+"     "+houseType;
		  	var color = roomObj.color;
		  	var price = roomObj.price==null?"0":roomObj.price;
		  	var totalPrice = roomObj.totalPrice==null?"0":roomObj.totalPrice;
		  	var buildingArea=roomObj.buildingArea==null?"0":roomObj.buildingArea;
		  	//建筑面积
		  	var method="roomCarInfo('"+roomObj.id+"')";
		  	var html='<div style="width:150px;height:80px;" ondblclick='+method+'><div style="width:20px;height:20px;position: absolute;right:5px;top:0px;"><input type="checkbox" name="chk_roomId" value="'+roomObj.id+'" roomStatus="'+roomObj.roomStatus+'" style="width: 15px; height: 15px;" /></div>面积:'+buildingArea+'㎡</br>单价:'+price+'元</br>总价:'+totalPrice+'元</div>';
		  	unit.add(createRoomPanle(str,color,html));
	  	}
  	}
}


function roomCarInfo(str){
	var treePrefix = str.substring(0,str.indexOf("_"));
	var title=null;
	if(treePrefix=="ROOM"){
		title="房间详情";
		if(roomWinView){
			 Ext.Msg.alert('提示', '没有权限,请联系管理员!');
		}else{
			//弹出详情框
			 var windowInfo = Ext.create('component.room.InfoWindow',{
				 roomId:getStrId(str)
			 });
			 windowInfo.show();
		}
	}
}
function createRoomPanle(title,color,html){
	return Ext.create('Ext.Panel', {
		 	frame: true,
        collapsible: true,
        title: title,
        width:160,
        height:100,
        layout:'column',
        bodyStyle:'background:'+color,
        collapsible: false,//可折叠  
        html:html,
	    defaults:{
	        	border:false        //去掉panel的边框  
	    	}
		});
}



//创建单元panel
function createPanle(title){
	return Ext.create('Ext.Panel', {
		frame: true,
     	collapsible: true,
     	title: title,
     	width:1100,
     	collapsible: false,//可折叠  
     	layout:'column',
	     	defaults:{
        	border:false        //去掉panel的边框  
		},
		tbar:[{
   			text:'批量销控',
   			icon:jypath+'/resources/ExtJSicons/flag/flag_pink.png',
			handler:function(){
				//选中记录
				var checkedCheckbox = $("input:checkbox[name='chk_roomId']:checked");
				if(checkedCheckbox.length == 0){
            		Ext.Msg.alert('提示', '请选择白色背景可售房源！');
            		return;
            	}
            	var roomIds = "";
            	var chooseFlag = false;
            	var validCount = 0;
				checkedCheckbox.each(function(){
					if($(this).attr("roomStatus") == "1"){
						if(roomIds){
                			roomIds += ",";
                		}
                		roomIds += $(this).val();
                		validCount += 1;
					}else{
						chooseFlag = true;
					}
				});
				roomIds = roomIds.replace(new RegExp(/ROOM_/g), "");
            	if(roomIds){
            		var msg = "选中【"+checkedCheckbox.length+"】条房源<br/>有效可售房源【" +validCount+ "】条<br/>是否确认进行销控?"
            		Ext.MessageBox.confirm("系统提示",msg, function(btn){
						if(btn == "yes"){
							var windowInfo = Ext.create('component.batch.sellControlWindow',{
								roomIds: roomIds,
							 	userName: userName
							});
							windowInfo.show();
						}
					});
            	}else{
            		Ext.Msg.alert('提示', '请选择白色背景的可售房源！');
            		return;
            	}
		    }
		},{
   			text:'批量撤控',
   			icon:jypath+'/resources/ExtJSicons/flag/flag_pink.png',
			handler:function(){
				//选中记录
				var checkedCheckbox = $("input:checkbox[name='chk_roomId']:checked");
				if(checkedCheckbox.length == 0){
            		Ext.Msg.alert('提示', '请选择蓝灰色背景销控房源！');
            		return;
            	}
            	var roomIds = "";
            	var chooseFlag = false;
            	var validCount = 0;
				checkedCheckbox.each(function(){
					if($(this).attr("roomStatus") == "6"){
						if(roomIds){
                			roomIds += ",";
                		}
                		roomIds += $(this).val();
                		validCount += 1;
					}else{
						chooseFlag = true;
					}
				});
				roomIds = roomIds.replace(new RegExp(/ROOM_/g), "");
            	if(roomIds){
            		var msg = "选中【"+checkedCheckbox.length+"】条房源<br/>有效销控房源【" +validCount+ "】条<br/>是否确认进行撤控?"
            		Ext.MessageBox.confirm("系统提示",msg, function(btn){
						if(btn == "yes"){
							var windowInfo = Ext.create('component.batch.sellCancelControlWindow',{
								roomIds: roomIds,
							 	userName: userName
							});
							windowInfo.show();
						}
					});
            	}else{
            		Ext.Msg.alert('提示', '请选择蓝灰色背景的销控房源！');
            		return;
            	}
		    }
		},{
			id: "btn_choose",
   			text:'全选',
   			icon:jypath+'/resources/ExtJSicons/anchor.png',
			handler:function(){
				//选中记录
				var checkedCheckbox = $("input:checkbox[name='chk_roomId']");
				var chooseText = Ext.getCmp("btn_choose").getText();
				checkedCheckbox.each(function(){
					if("全选" == chooseText){
						$(this).prop("checked", true);
					}else{
						$(this).prop("checked", false);
					}
				});
				if("全选" == chooseText){
					Ext.getCmp("btn_choose").setText("全不选");
				}else{
					Ext.getCmp("btn_choose").setText("全选");
				}
		    }
		}]
	});
}